﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Ldt.InformationUnit.Common;
using LdtDataEngin.ModuleDetail.BaseModule;
using LdtDataEngin.ModuleDetail.ParagraphAnalysis;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.XmlUtility;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.Model;
using LdtJudge.DataEngine.Model.DataModel.DataParseStorage;
using LdtJudge.DataEngine.Model.XMLConfigModel.ConfigModel;
using Newtonsoft.Json;

namespace LdtDataEngin.ModuleDetail.AnalysisModule.ParagraphAnalysis
{
    /// <summary>
    /// 段落提取模块
    /// 输入信息:1.格式化后的文本内容===>DataContext.DyData_Analysis
    ///          2.段落提取的配置信息===>DataContext.DataLayerSysStores
    /// 输出信息:将段落信息保存到了DataContext.DyData_Analysis.Duanluos
    /// </summary>
    public class ParagraphAssemble : AssermBase
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">上下文内容</param>
        /// <param name="moudleName">模块名称</param>
        public ParagraphAssemble(DataContext context, string moudleName)
        {
            dataContext = context;
            base.MoudleName = moudleName;
        }

        /// <summary>
        /// 提取执行函数
        /// </summary>
        public void Extrat()
        {
            var configModel = dataContext.DataLayerSys.GetConfigModel(MoudleName);

            if (configModel != null)
            {
                ConfigRootModel configRootModel = ParseStepConfig(configModel);
                // 获取机器学习开关，如果开关是1执行机器学习的段落提取instrumentheadcasecode
                if (configRootModel.mlflag == "1")
                {
                    ParagraphAI paragraphAI = new ParagraphAI(dataContext);
                    paragraphAI.AIExtract();
                }
                else
                {
                    List<ConfigStateModel> configModels = configRootModel.configStateModelList;
                    if (configRootModel.type == "1")
                    {
                        ParagraphLocation paragraphLocation = new ParagraphLocation() { dataContext = dataContext };
                        paragraphLocation.Extrat(configModels, MoudleName);
                    }
                    else
                    {
                        foreach (ConfigStateModel item in configModels)
                        {
                            //段落编号变为小写
                            item.code = item.code.ToLower();
                            // 执行完机器学习的段落提取，再执行其他方式的段落提取

                            if (item.executetype == "reg")
                            {
                                // 执行正则的时候需要注意，如果当前正则编码代表的段落已经在机器学习中提取出来，那么直接将机器学习的结果拷贝过来即可
                                ParagraphReg paragraphReg = new ParagraphReg(dataContext);
                                paragraphReg.Extract(item, MoudleName);
                            }
                            else if (item.executetype == "dll")
                            {
                                // 动态执行动态库
                                ParagraphDLL dllParagraph = new ParagraphDLL(dataContext);
                                dllParagraph.Extract(item.executefile, MoudleName);
                            }
                        }

                        //民事法庭笔录特殊处理
                        if (dataContext.DataLayerAns.CaseType.ToLower() == "b1" && dataContext.DataLayerAns.SourceCode.ToLower() == "mscourtrecord")
                        {
                            CourtRecordSpecial();
                        }

                        //20240110syjie，对机器学习的逻辑分段进行特殊处理
                        ParagraphMLSpecial();
                    }
                }
            }
        }

        #region 民事法庭笔录特殊处理

        /// <summary>
        /// 
        /// </summary>
        private void CourtRecordSpecial()
        {
            Regex reg = new Regex("[^\r]+");
            //获取相关配置;

            var paraList = dataContext.DataLayerAns.Duanluos;//分段对象集合  
            Regex reg_space = new Regex(@"^[\r\n]+(?![\s]+)|^[\r\n]+$|(?<=[\S]+(\r(?!\n)|(?<!\r)\n|\r\n))[\r\n]+(?=[\r\n]+)", RegexOptions.Singleline);

            #region 法庭核对原告证据(ms_cr_checkplaintiffevidence)=原告举证(ms_cr_plaintiffevidence)-原告举证内容(ms_cr_suitevid)-被告质证(ms_cr_defendantopinion)
            //原告举证
            var paragraphPlaintiffEvidence = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_plaintiffevidence").ToList();
            //原告举证内容
            var paragraphEvid = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_suitevid").ToList();
            //被告质证
            var paragraphAccusedPersonProof = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_defendantopinion").ToList();
            string EvidenceCentent = string.Join("", paragraphPlaintiffEvidence.Select(contet => contet.Duanluoneirong));
            var qusuitevid = paragraphEvid.Select(contet => contet.Duanluoneirong).ToList();
            var AccusedProof = paragraphAccusedPersonProof.Select(contet => contet.Duanluoneirong).ToList();
            string b1checkappellantevidence = EvidenceCentent;
            if (qusuitevid != null && qusuitevid.Count > 0)
            {//进行替换原告举证内容
                foreach (var evid in qusuitevid)
                {
                    if (!string.IsNullOrEmpty(evid))
                    {
                        MatchCollection ites = reg.Matches(evid);
                        foreach (var Child in ites)
                        {
                            b1checkappellantevidence = b1checkappellantevidence.Replace(Child.ToString(), "");
                        }
                    }

                }

            }
            if (AccusedProof != null && AccusedProof.Count > 0)
            {//替换被告质证部分内容
                foreach (var Aproff in AccusedProof)
                {
                    MatchCollection ites = reg.Matches(Aproff);
                    foreach (var Child in ites)
                    {
                        b1checkappellantevidence = b1checkappellantevidence.Replace(Child.ToString(), "");
                    }
                }

            }


            //处理得到结果正文中有换行
            b1checkappellantevidence = b1checkappellantevidence.Trim();
            b1checkappellantevidence = Regex.Replace(b1checkappellantevidence, "(?<=\r)[\r]+", "");
            b1checkappellantevidence = reg_space.Replace(b1checkappellantevidence, "");

            //分段实体类;
            An_duanluo MParagraph = new An_duanluo();
            //对段落对象赋值
            MParagraph.Duanluoid = Snowflake.Instance().GetId().ToString(); ;//创建一个分段的ID;
            MParagraph.Duanluoneirong = b1checkappellantevidence;
            //MParagraph.SD_ID = "";
            MParagraph.Duanluobianhao = "MS_CR_CheckPlaintiffEvidence";
            //将分段的对象数据放入到数据层数据
            dataContext.DataLayerAns.Duanluos.Add(MParagraph);

            #endregion

            #region 原告对被告答辩的补充意见（MS_CR_PlaintiffSupplementSuggest）=原告陈述诉请及事实理由-原告诉请(ms_cr_suitinfo)-原告事实(ms_cr_suitfact)-被告答辩（ms_cr_defendantsuggest）
            //原告陈述诉请及事实理由
            var PlaintiffSuitInfoAndFact = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_suitinfoandfact").ToList();
            //原告诉请
            var PlaintiffSuitinfo = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_suitinfo").ToList();
            //原告事实
            var PlaintiffSuitFact = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_suitfact").ToList();
            ///被告答辩
            var DefendSuggest = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_defendantsuggest").ToList();

            string PlaintiffCentent = string.Join("", PlaintiffSuitInfoAndFact.Select(contet => contet.Duanluoneirong));
            if (PlaintiffSuitinfo != null && PlaintiffSuitinfo.Count > 0)
            {
                foreach (var model in PlaintiffSuitinfo)
                {
                    if (!string.IsNullOrWhiteSpace(model.Duanluoneirong))
                    {
                        Regex ret = new Regex(@"[^\r]+", RegexOptions.Singleline);
                        MatchCollection matchs = ret.Matches(model.Duanluoneirong);
                        foreach (Match match in matchs)
                        {
                            Regex r = new Regex(@"(^[^审长问？?][^\r]*[:：])(?=现?变更诉讼请求(如下)?|诉讼请求变更为|现要求|现主张)", RegexOptions.Singleline);
                            string mat = r.Replace(match.Value, "");
                            if (!string.IsNullOrEmpty(mat.Trim()))
                            {
                                PlaintiffCentent = PlaintiffCentent.Replace(mat.ToString().Trim(), "");
                            }
                        }
                    }

                }
            }
            if (PlaintiffSuitFact != null && PlaintiffSuitFact.Count > 0)
            {
                foreach (var model in PlaintiffSuitFact)
                {
                    if (!string.IsNullOrWhiteSpace(model.Duanluoneirong))
                    {
                        PlaintiffCentent = PlaintiffCentent.Replace(model.Duanluoneirong.ToString().Trim(), "");
                    }
                }
            }
            if (DefendSuggest != null && DefendSuggest.Count > 0)
            {
                foreach (var model in DefendSuggest)
                {
                    MatchCollection matchs = reg.Matches(model.Duanluoneirong);
                    foreach (Match match in matchs)
                    {
                        if (!string.IsNullOrEmpty(match.ToString().Trim()))
                        {
                            PlaintiffCentent = PlaintiffCentent.Replace(match.ToString().Trim(), "");
                        }
                    }
                }
            }


            //处理得到结果正文中有换行
            PlaintiffCentent = PlaintiffCentent.Trim();
            PlaintiffCentent = Regex.Replace(PlaintiffCentent, "(?<=\r)[\r]+", "");
            PlaintiffCentent = reg_space.Replace(PlaintiffCentent, "");

            //decimal serialNumbSuggest = base.dytable.BaseSysTable.ConfigParagraph.Rows.OfType<DataRow>().FirstOrDefault(code => code.Field<string>("CDL_Code") == "MS_CR_PlaintiffSupplementSuggest").Field<decimal>("CDL_ShowIndex");
            //分段实体类;
            An_duanluo MParagraphSuggest = new An_duanluo();
            //对段落对象赋值
            MParagraphSuggest.Duanluoid = Snowflake.Instance().GetId().ToString(); ;//创建一个分段的ID;
            MParagraphSuggest.Duanluoneirong = PlaintiffCentent;
            //MParagraphSuggest.SD_ID = "";
            MParagraphSuggest.Duanluobianhao = "MS_CR_PlaintiffSupplementSuggest";
            MParagraphSuggest.Duanluoxuhao = 0;
            //将分段的对象数据放入到数据层数据
            dataContext.DataLayerAns.Duanluos.Add(MParagraphSuggest);


            #endregion

            #region 法官补充发问(MS_CR_JudgeSupplementInquire)=被告举证(MS_CR_AccusedPersonProof)-被告举证内容(MS_CR_AnswerEvidence)-原告质证(MS_CR_PlaintiffCross-examination)

            //被告举证
            var DefendPersonProof = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_accusedpersonproof").ToList();
            //被告举证内容
            var DefendEvidence = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_answerevidence").ToList();
            //原告质证
            var Defendplaintiffcross = paraList.Where(pet => pet.Duanluobianhao.ToLower() == "ms_cr_plaintiffcross-examination").ToList();

            string DefendCentent = string.Join("", DefendPersonProof.Select(contet => contet.Duanluoneirong));
            if (DefendEvidence != null && DefendEvidence.Count > 0)
            {
                foreach (var model in DefendEvidence)
                {
                    if (!string.IsNullOrWhiteSpace(model.Duanluoneirong))
                    {
                        MatchCollection matchs = reg.Matches(model.Duanluoneirong);
                        foreach (var ite in matchs)
                        {
                            if (!string.IsNullOrEmpty(ite.ToString()))
                            {
                                DefendCentent = DefendCentent.Replace(ite.ToString(), "");
                            }
                        }
                    }

                }
            }
            if (Defendplaintiffcross != null && Defendplaintiffcross.Count > 0)
            {
                foreach (var model in Defendplaintiffcross)
                {
                    MatchCollection ites = reg.Matches(model.Duanluoneirong);
                    foreach (var ite in ites)
                    {
                        if (!string.IsNullOrEmpty(ites.ToString()))
                        {
                            DefendCentent = DefendCentent.Replace(ite.ToString(), "");
                        }
                    }
                }
            }

            //处理得到结果正文中有换行
            DefendCentent = DefendCentent.Trim();
            DefendCentent = Regex.Replace(DefendCentent, "(?<=\r)[\r]+", "");
            DefendCentent = reg_space.Replace(DefendCentent, "");

            //decimal serialNumbJudgeSupplement = base.dytable.BaseSysTable.ConfigParagraph.Rows.OfType<DataRow>().FirstOrDefault(code => code.Field<string>("CDL_Code") == "MS_CR_JudgeSupplementInquire").Field<decimal>("CDL_ShowIndex");
            //分段实体类;
            An_duanluo MParagraphJudge = new An_duanluo();
            //对段落对象赋值
            MParagraphJudge.Duanluoid = Snowflake.Instance().GetId().ToString(); ;//创建一个分段的ID;
            MParagraphJudge.Duanluoneirong = DefendCentent;
            //MParagraphJudge.SD_ID = "";
            MParagraphJudge.Duanluobianhao = "MS_CR_JudgeSupplementInquire";
            MParagraphJudge.Duanluoxuhao = 0;
            //将分段的对象数据放入到数据层数据
            //dataLayerStores.AnalysisParameter.sourceDossierInfo.SD_ParagraphTXTList.Add(MParagraphJudge);
            dataContext.DataLayerAns.Duanluos.Add(MParagraphJudge);

            #endregion

        }

        #endregion

        #region 对机器学习的逻辑分段进行特殊处理

        /// <summary>
        /// 对机器学习的逻辑分段进行特殊处理
        /// 20240110syjie
        /// </summary>
        private void ParagraphMLSpecial()
        {
            //拉取配置文件
            ParagraphMLConfigModel paragraphMLConfigModel = GetParagraphMlConfig();
            if (paragraphMLConfigModel != null && paragraphMLConfigModel.caseTypeConfigList != null)
            {
                //与配置的条件一致，才处理
                var itemConfig = paragraphMLConfigModel.caseTypeConfigList.Find(m => m.code?.ToLower() == dataContext.DataLayerAns.CaseType.ToLower()
                                                                                  && m.booketype?.ToLower() == dataContext.DataLayerAns.SourceCode.ToLower()
                                                                                  && m.appid?.ToLower() == dataContext.DataLayerAns.AppId.ToLower());

                if (itemConfig != null)
                {
                    dataContext.DataLayerAns.Duanluos = JoinParagraph(itemConfig.paragraphList, dataContext.DataLayerAns.Duanluos);
                }
            }
        }

        /// <summary>
        /// 获取机器学习的逻辑分段的配置文件
        /// </summary>
        private ParagraphMLConfigModel GetParagraphMlConfig()
        {
            ParagraphMLConfigModel paragraphMLConfigModel = new ParagraphMLConfigModel();

            //拉取配置文件
            Dictionary<string, string> dicElement = new Dictionary<string, string>();
            dicElement.Add("fileFullName", @"config/moduleconfig/commonconfig/generalconfig/paragraph_mlconfig/paragraph_mlconfig.xmlldt");
            string elementMessage = WebUtil.DoGet(ConfigRetrieval.GetConfigRetrieval.GetAppSettingString("systemapi") + "/api/WordParse/GetConfigFileContent", dicElement, "utf-8");

            //解析配置
            dynamic elementcofig = JsonConvert.DeserializeObject<dynamic>(elementMessage);
            if (elementcofig.result.code.ToString() == "1")
            {
                string elementcofigstr = elementcofig.body;
                paragraphMLConfigModel = XmlUtility.DeserializeToObject<ParagraphMLConfigModel>(elementcofigstr);
            }

            return paragraphMLConfigModel;
        }

        /// <summary>
        /// 拼接逻辑分段
        /// </summary>
        /// <param name="paragraphList"></param>
        /// <param name="listDuanluoOld"></param>
        /// <returns></returns>
        private List<An_duanluo> JoinParagraph(List<ParagraphConfig> paragraphList, List<An_duanluo> listDuanluoOld)
        {
            List<An_duanluo> listDuanluoNew = new List<An_duanluo>();

            if (paragraphList != null && listDuanluoOld != null)
            {
                int levelCode = 0;
                foreach (var item in paragraphList)
                {
                    //从结果中找到该段落
                    var duanluo = listDuanluoOld.Find(m => m.Duanluobianhao?.ToLower() == item.convertcode?.ToLower());
                    if (duanluo != null)
                    {
                        if (!string.IsNullOrWhiteSpace(item.targetcode))
                        {
                            duanluo.Duanluobianhao = item.targetcode;//修改段落编号
                        }
                        duanluo.DuanluoxuhaoDesc = (++levelCode).ToString();//修改段落序号
                        listDuanluoNew.Add(duanluo);

                        //处理子级
                        if (item.childrenList != null)
                        {
                            //子级逻辑段
                            List<An_duanluo> listDuanluoChildren = JoinParagraph(item.childrenList, listDuanluoOld);
                            int levelCodeChild = 0;
                            foreach (var child in listDuanluoChildren)
                            {
                                //修改父级ID
                                child.Duanluofujiid = duanluo.Duanluoid;
                                //修改段落序号（层级）
                                child.DuanluoxuhaoDesc = string.Format("{0}.{1}", duanluo.DuanluoxuhaoDesc, ++levelCodeChild);
                            }
                            listDuanluoNew.AddRange(listDuanluoChildren);
                        }
                    }
                }
            }

            return listDuanluoNew;
        }

        #endregion
    }
}
